﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using CID.Execution.Agent.Service.Configuration;
using CID.Execution.Agent.Support;
using CID.Execution.Support;
using CID.Execution.Support.Contracts;
using NailsFramework.IoC;

namespace CID.Execution.Agent.Service.Support
{
    [Lemming(Singleton = true)]
    public class ControllerServiceProxyFactory : IControllerServiceProxyFactory
    {
        private ChannelFactory<IControllerService> channelFactory;
        public ControllerServiceProxyFactory()
        {
            channelFactory = new ChannelFactory<IControllerService>(new BasicHttpBinding());
        }

        public IControllerService Create()
        {
            return channelFactory.CreateChannel(GetEndpointAddress());
        }

        public void Dispose(IControllerService controllerServiceProxy)
        {
            if (controllerServiceProxy is IChannel)
                (controllerServiceProxy as IChannel).Close();
        }

        private static EndpointAddress GetEndpointAddress()
        {
            return new EndpointAddress(UrlProvider.GetDeploymentControllerUrl(ApplicationConfiguration.ControllerAddress));
        }
    }
}
